package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 地址簿 服务实现类
 *
 * @author alkaid
 * @since 2024-02-24
 */
@Service
@Slf4j
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public List<AddressBook> list(Long userId) {

        return addressBookMapper.selectList(
                new LambdaQueryWrapper<AddressBook>()
                        .eq(AddressBook::getUserId, userId)
        );
    }

    @Override
    public void create(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.insert(addressBook);
    }

    @Override
    public AddressBook getDefaultAddress() {
        return addressBookMapper.selectOne(
                new LambdaQueryWrapper<AddressBook>()
                        .eq(AddressBook::getUserId, BaseContext.getCurrentId())
                        .eq(AddressBook::getIsDefault, 1)
        );
    }

    @Override
    public void setDefaultAddress(AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();

        // 查询用户全部地址
        List<AddressBook> addressBookList = list(userId);

        // 逐个设置为非默认地址
        for (AddressBook addressBookTemp : addressBookList) {
            addressBookTemp.setIsDefault(0);
            addressBookMapper.updateById(addressBookTemp);
        }

        AddressBook addressBookDefault = addressBookMapper.selectById(addressBook.getId());
        addressBookDefault.setIsDefault(1);

        // 设置当前地址为默认地址
        addressBookMapper.updateById(addressBookDefault);
    }


}
